<?php

class I18N extends PrspLibrary{

	private static $lang;
	
	public function initial(){}
	
	public function getSelfPluginId(){
		$pluginId = str_replace(PLUGINS_PATH, '', __FILE__);
		return substr($pluginId,1,strpos($pluginId, '/', 2)-1);
	}
	
	/**
	 * load i18n file
	 *
	 * @param String plugin id
	 */
	private function loadFile( $pluginId ){
		if( $pluginId==null ){
			Logger::error('PluginId is null');
		}else{
			$filename = PLUGINS_PATH.'/'.$pluginId.'/lang/'.I18N::getLanguage().'.php';
			if( !is_file($filename) ){
				Logger::info('I18N language file not found : '.$filename);
			}else{
				unset($lang);
				include $filename;
				if(isset($lang)){
					I18N::$lang[$pluginId] = $lang;
				}
				Logger::debug('Load I18N language file : '.$filename);
			}
		}
	}

	/**
	 * Get I18N String
	 *
	 * @param String plugin id
	 * @return array I18N String
	 */
	public function getI18N( $pluginId=null ){
		if( $pluginId==null ){
			$pluginId = Runtime::getPluginId();
		}
		if( !isset(I18N::$lang[$pluginId]) ){
			I18N::loadFile($pluginId);
		}
		if( isset(I18N::$lang[$pluginId]) ){
			return I18N::$lang[$pluginId];
		}else{
			return null;
		}
	}
	
	/**
	 * Get I18N String
	 * @see I18N::getString
	 * @param String key
	 * @param String plugin id
	 * @return String
	 */
	public function _( $key, $pluginId=null ){
		return I18N::getString( $key, $pluginId );
	}
	
	/**
	 * Get I18N String
	 *
	 * @param String key
	 * @param String plugin id
	 * @return String
	 */
	public function getString( $key, $pluginId=null ){
		if( $pluginId==null ){
			$pluginId = Runtime::getPluginId();
		}
		if( !isset(I18N::$lang[$pluginId]) ){
			I18N::loadFile($pluginId);
		}
		if( isset(I18N::$lang[$pluginId][$key]) ){
			return I18N::$lang[$pluginId][$key];
		}else{
			return '!!'.$key.'!!';
		}	
	}

	/**
	 * Get language property
	 *
	 * @return String language property
	 */
	public static function getLanguage() {
		
		if( SessionUtility::getValue( '_Language', I18N::getSelfPluginId())==null ){
			$extensionPoints = Register::getExtension('Configuration', I18N::getSelfPluginId());
			if( count($extensionPoints)>0 ){
				$extension = array_pop($extensionPoints);
				if( isset($extension['DefaultLanguage']) ){
					I18N::setLanguage($extension['DefaultLanguage']);
				}
			}
		}
		return SessionUtility::getValue( '_Language', I18N::getSelfPluginId());
	}
	
	/**
	 * Set language property
	 *
	 * @param String language property
	 */
	public static function setLanguage($language) {
		SessionUtility::setValue( '_Language', $language, I18N::getSelfPluginId());
	}
	
}

?>